import time
import requests
from selenium import webdriver

url = "https://www.douban.com/"
browser = webdriver.Chrome(executable_path="/Users/great/Downloads/chromedriver")


# 定义一个方法
def login():
    # 通过selenium模拟登陆豆瓣
    username = "18629433376"
    password = "ys199602161119"
    browser.get(url)
    time.sleep(3)
    browser.switch_to.frame(browser.find_element_by_tag_name("iframe"))

    # 找到账号登陆的按钮
    login_ele = browser.find_element_by_xpath("//li[@class='account-tab-account']")

    # 点击账号登录按钮
    login_ele.click()
    username_ele = browser.find_element_by_xpath("//input[@id='username']")
    password_ele = browser.find_element_by_xpath("//input[@id='password']")
    username_ele.send_keys(username)
    password_ele.send_keys(password)

    submit = browser.find_element_by_xpath("//a[@class='btn btn-account btn-active']")
    submit.click()

    time.sleep(10)
    cookies = browser.get_cookies()
    cookie_dict = {}
    for item in cookies:
        cookie_dict[item["name"]] = item["value"]
    res = requests.get(url,cookies=cookie_dict)
    if "great" in res.text:
        print("已登陆")
    print(browser.get_cookies())


if __name__ == "__main__":
    login()
